package com.yjhb.android.sbz.http;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.BuildConfig;
import com.yjhb.android.sbz.manager.OSSManager;
import com.yjhb.android.sbz.mvp.UploadApi;
import com.yjhb.android.sbz.tool.DataSaveTool;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.entity.Result;
import com.jojo.android.zxlib.interfaces.Callback;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * 创建者 zx
 * 创建时间 2020/12/24 10:30
 */
public class UploadTool {
    private final String TAG = "UploadTool";

    public static void upLoadFile(List<LocalMedia> medias, Retrofit retrofit, Observer<String> observer) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                for (LocalMedia media : medias) {
                    File file = new File(media.getCompressPath());
                    if (!file.exists()) {
                        e.onError(new Throwable("文件不存在！请重新选择"));
                        return;
                    }
                    RequestBody body = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
                    Call<Result<String>> call = retrofit.create(UploadApi.class).getUploadAvatarUrl(App.userInfo.getId(),
                            MultipartBody.Part.createFormData("file", file.getName(), body));
                    Result<String> result = call.execute().body();
                    if (result == null) {
                        e.onError(new Throwable("图片上传失败，请重试！"));
                        return;
                    }
                    if (result.getCode() != 200) {
                        e.onError(new Throwable("图片上传失败，错误码：" + result.getCode() + " 请重试！"));
                        return;
                    }
                    e.onNext(result.getData());
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io()) //在IO线程执行网路请求
                .observeOn(AndroidSchedulers.mainThread()) //在UI线程得到数据
                .subscribe(observer);

    }

    /**
     * @param medias
     * @param watermark 是否加水印
     * @param retrofit
     * @param observer
     */

    public static void upLoadImages(List<LocalMedia> medias, boolean watermark, Retrofit retrofit, Observer<String> observer) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                if (medias != null) {
                    for (LocalMedia media : medias) {
                        //获取本地文件  判断文件是否存在
                        File file = new File(media.getPath());
                        if (!file.exists()) {
                            e.onError(new Throwable("图片不存在！请重新选择"));
                            return;
                        }
                        //压缩图片
                        File img = Tool.compressImage(file, watermark);
                        //将图片上传
                        RequestBody body = RequestBody.create(MediaType.parse("application/otcet-stream"), img);
                        Call<Result<String>> call = retrofit.create(UploadApi.class).getUploadAvatarUrl(App.userInfo.getId(),
                                MultipartBody.Part.createFormData("file", img.getName(), body));
                        Result<String> result = call.execute().body();
                        if (result == null) {
                            e.onError(new Throwable("图片上传失败，请重试！"));
                            return;
                        }
                        if (result.getCode() != 200) {
                            e.onError(new Throwable("图片上传失败，错误码：" + result.getCode() + " 请重试！"));
                            return;
                        }
                        e.onNext(result.getData());
                    }
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io()) //在IO线程执行网路请求
                .observeOn(AndroidSchedulers.mainThread()) //在UI线程得到数据
                .subscribe(observer);

    }


    public static void OSSUploadImages(List<LocalMedia> medias, boolean watermark, Observer<String> observer) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                if (medias != null) {
                    for (LocalMedia media : medias) {
                        //获取本地文件  判断文件是否存在
                        File file = new File(media.getPath());
                        if (!file.exists()) {
                            e.onError(new Throwable("图片不存在！请重新选择"));
                            return;
                        }
                        //压缩图片
                        File img = Tool.compressImage(file, watermark);
                        //将图片上传到文件服务器，如果是体验服务器和正式服上传到release文件夹，
                        //否则上传到test文件夹
                        String dir = null;
                        switch (DataSaveTool.getHost()) {
                            case BuildConfig.ServerURL_RELEASE:
                            case BuildConfig.ServerURL_ALPHA:
                                dir = "imgV4/release/common";
                                break;
                            default:
                                dir = "imgV4/test/common";
                        }
                        PutObjectResult result = OSSUploadFile(img.getAbsolutePath(),
                                dir,
                                img.getName(), new Callback<Long[]>() {
                            @Override
                            public void callback(Long[] longs) {

                            }
                        });
                        if (result == null) {
                            e.onError(new Throwable("图片上传失败，请重试！"));
                            return;
                        }
                        if (result.getStatusCode() != 200) {
                            e.onError(new Throwable("图片上传失败，错误码：" + result.getStatusCode() + " 请重试！"));
                            return;
                        }
                        e.onNext(OSSManager.getUrl(dir,img.getName()));
                    }
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io()) //在IO线程执行网路请求
                .observeOn(AndroidSchedulers.mainThread()) //在UI线程得到数据
                .subscribe(observer);
    }



    /**
     * 同步上传OSS文件
     * @param path
     * @param fileName
     * @param progressCallback
     * @return
     */
    public static PutObjectResult OSSUploadFile(String path,String dir,String fileName, Callback<Long[]> progressCallback) {
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest(OSSManager.BUCKET_NAME,
                dir+"/" + fileName, path);
        // 异步上传时可以设置进度回调。
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                ZxLogTool.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                if (progressCallback != null) {
                    progressCallback.callback(new Long[]{currentSize, totalSize});
                }
            }
        });
        try {
           return OSSManager.getInstance().getOss().putObject(put);
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return null;
    }

}
